﻿namespace Smark.Core
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Security.Cryptography;
    using System.Text;

    public class DESCrypto
    {
        private DESCryptoServiceProvider key = new DESCryptoServiceProvider();

        public byte[] Decrypt(byte[] data)
        {
            IList<byte> list = new List<byte>();
            MemoryStream stream = new MemoryStream(data);
            CryptoStream stream2 = new CryptoStream(stream, this.key.CreateDecryptor(), CryptoStreamMode.Read);
            for (int i = stream2.ReadByte(); i >= 0; i = stream2.ReadByte())
            {
                list.Add((byte) i);
            }
            stream2.Close();
            stream.Close();
            byte[] array = new byte[list.Count];
            list.CopyTo(array, 0);
            return array;
        }

        public string Decrypt(string data)
        {
            return Encoding.UTF8.GetString(this.Decrypt(Convert.FromBase64String(data)));
        }

        public byte[] Encrypt(byte[] data)
        {
            MemoryStream stream = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, this.key.CreateEncryptor(), CryptoStreamMode.Write);
            stream2.Write(data, 0, data.Length);
            stream2.Close();
            byte[] buffer = stream.ToArray();
            stream.Close();
            return buffer;
        }

        public string Encrypt(string data)
        {
            return Convert.ToBase64String(this.Encrypt(Encoding.UTF8.GetBytes(data)));
        }

        public DESInfo KeyInfo
        {
            get
            {
                DESInfo info = new DESInfo();
                if (this.PublicRas != null)
                {
                    info.Key = this.PublicRas.Encrypt(this.key.Key);
                    info.IV = this.PublicRas.Encrypt(this.key.IV);
                    return info;
                }
                info.Key = this.key.Key;
                info.IV = this.key.IV;
                return info;
            }
            set
            {
                if (this.PrivateRas != null)
                {
                    this.key.Key = this.PrivateRas.Decrypt(value.Key);
                    this.key.IV = this.PrivateRas.Decrypt(value.IV);
                }
                else
                {
                    this.key.Key = value.Key;
                    this.key.IV = value.IV;
                }
            }
        }

        public RasCrypto PrivateRas { get; set; }

        public RasCrypto PublicRas { get; set; }

        public class DESInfo
        {
            public byte[] IV { get; set; }

            public byte[] Key { get; set; }
        }
    }
}

